package ua.at.tsvetkov.webservices.parsers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONException;

import ua.at.tsvetkov.util.Log;

public abstract class AbstractParserJSON {

	/**
	 * Parse input stream. NOT CLOSE input stream after finish.
	 * 
	 * @param in input stream.
	 * @return true if parsing was successful.
	 * @throws IOException
	 * @throws JSONException
	 */
	public boolean parse(InputStream in) throws IOException, JSONException {
		if (in == null) {
			Log.w("InputStream is null. Parsing aborted.");
			return false;
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String line;
		StringBuffer buffer = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
		}
		return process(buffer.toString().trim());
	}

	/**
	 * Processing input data.
	 * 
	 * @param data JSON string.
	 * @return true if parsing was successful.
	 */
	public abstract boolean process(String dataString) throws JSONException;

}
